package com.scwatch.ext.wowza;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;

@Component
public class wowzaTools {

    String serverurl = "192.168.32.201:8087";

    String url = "rtmp://192.168.32.201:1935";

    private static final Logger logger = LoggerFactory.getLogger(wowzaTools.class);

    //region 调用wowza的方法
    public wowzaTools(String serverurl,String url){
        this.serverurl=serverurl;
        this.url = url;
    }
//    public  static void  main(String[] s){
//        wowzaTools tools = new wowzaTools("192.168.32.201:8087", "rtmp://192.168.32.201:1935");
//        tools.DeleteApplicationName("livexxxxx002");
//    }

    /**
     * 创建wowza 应用
     *
     * @param ApplicationName
     */
    public boolean CreateApplication(String ApplicationName) {
        String targetURL1 = "http://" + serverurl + "/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/" + ApplicationName;
        wowzaCreate wowzaCreate = new wowzaCreate();
        wowzaCreate.setRestURI("http://" + serverurl + "/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/" + ApplicationName);
        wowzaCreate.setName(ApplicationName);
        wowzaCreate.setAppType("Live");
        wowzaCreate.setClientStreamReadAccess("*");
        wowzaCreate.setClientStreamWriteAccess("*");
        wowzaCreate.setDescription("");

        wowzaCreate.StreamConfigBean streamConfigBean = new wowzaCreate.StreamConfigBean();
        streamConfigBean.setRestURI("http://" + serverurl + "/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/" + ApplicationName + "/streamconfiguration");
        streamConfigBean.setStreamType("live");
        streamConfigBean.setLiveStreamPacketizer(new String[]{"cupertinostreamingpacketizer","mpegdashstreamingpacketizer","smoothstreamingpacketizer"});
        wowzaCreate.setStreamConfig(streamConfigBean);

        JSONObject jsonObject = httpPost(targetURL1, JSONObject.toJSONString(wowzaCreate));

        if (jsonObject == null) {
            return false;
        }

        return true;
    }

    /**
     * 获取应用信息
     *
     * @param ApplicationName
     */
    public boolean hasApplicationInfo(String ApplicationName) {
        String targetURL1 = "http://" + serverurl + "/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/" + ApplicationName;
        JSONObject jsonObject = httpGet(targetURL1);

        if (jsonObject == null) {
//            wowzaapplcationinfo appinfo = JSONObject.parseObject(jsonObject.toJSONString(), wowzaapplcationinfo.class);
            return false;
        }
        return true;

    }

    /**
     * 获取应用列表
     */
    public void GetApplicationList() {
        String targetURL1 = "http://" + serverurl + "/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications";
        JSONObject jsonObject = httpGet(targetURL1);
    }


//    public void CreateStreamsource(String Application, String name) {
//        String targetURL1 = "http://" + serverurl + "v2/servers/_defaultServer_/publishers";
//        JSONObject jsonObject = httpPost(targetURL1, JSONObject.toJSONString(wowzaCreate));
//    }

    /**
     * 获取输入流列表
     *
     * @param application
     */
    public void GetStreamfileList(String application) {
        String targetURL1 = "http://" + serverurl + "v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/" + application + "/streamfiles";
        JSONObject jsonObject = httpGet(targetURL1);
    }


    /**
     * 获取输入流详情
     *
     * @param application
     * @param streamfile
     */
    public boolean GetStreamFileInfo(String application, String streamfile) {
        String targetURL1 = "http://" + serverurl + "v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/" + application + "/streamfiles/" + streamfile;
        JSONObject jsonObject = httpGet(targetURL1);
        if (jsonObject != null) {
            return false;
        }
        return true;
    }


    /**
     * 创建
     *
     * @param application
     * @param streamfile
     */
    public boolean CreateStreamFile(String application, String streamfile) {

        String targetURL1 = "http://" + serverurl + "/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/streamfiles";
        createstreamfile file = new createstreamfile();
        file.setName(application + streamfile);
        file.setServerName("_defaultServer_");
        file.setUri(url);
        JSONObject jsonObject = httpPost(targetURL1, JSON.toJSONString(file));

        if (jsonObject != null) {
            return false;
        }
        return true;
    }

    //删除 应用名称
    public boolean DeleteApplicationName( String applicationName) {
        String targetUrl = "http://" + serverurl + "/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/"+ applicationName;
        JSONObject jsonObject = httpDel(targetUrl);

        if (jsonObject == null) {
            return false;
        }
        return true;
    }

    /**
     * 删除输入流文件
     *
     * @param application
     * @param streamfile
     */
    public boolean DeleteStreamFile(String application, String streamfile) {
        String targetUrl = "http://" + serverurl + "/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/streamfiles/"+ streamfile;
        JSONObject jsonObject = httpDel(targetUrl);

        if (jsonObject == null) {
            return false;
        }
        return true;
    }
    //endregion

    //region 网络请求

    /**
     * httpPost
     *
     * @param url         路径
     * @param //jsonParam 参数
     * @return
     */
    public JSONObject httpPost(String url, String Param) {
        return httpPost(url, Param, false);
    }

    /**
     * post请求
     *
     * @param url            url地址
     * @param //jsonParam    参数
     * @param noNeedResponse 不需要返回结果
     * @return
     */
    public JSONObject httpPost(String url, String Param, boolean noNeedResponse) {
        //post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            method.addHeader("Content-type", "application/json; charset=utf-8");
            method.addHeader("Accept", "application/json; charset=utf-8");
            method.setEntity(new StringEntity(Param, Charset.forName("UTF-8")));

            HttpResponse result = httpClient.execute(method);
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 201 || result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (Exception e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public JSONObject httpGet(String url) {
        //get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //发送get请求
            HttpGet request = new HttpGet(url);
            request.addHeader("Content-type", "application/json; charset=utf-8");
            request.addHeader("Accept", "application/json; charset=utf-8");
            HttpResponse response = httpclient.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonResult;
    }


    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public JSONObject httpDel(String url) {
        //get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //发送get请求
            HttpDelete request = new HttpDelete(url);
            request.addHeader("Content-type", "application/json; charset=utf-8");
            request.addHeader("Accept", "application/json; charset=utf-8");
            HttpResponse response = httpclient.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonResult;
    }
    //endregion

}
